<template>
  <el-dialog
    draggable
    overflow
    v-model="visible"
    :title="titleMap[mode]"
    :width="1024"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <sc-water-mark ref="wm" text="已审核" :color="'rgba(128,128,128,0.1)'">
      <el-form
        :model="form"
        :rules="rules"
        ref="dialogForm1"
        label-width="70px"
        label-position="top"
        class="formhead"
      >
        <el-row style="display: flex; align-items: center">
          <el-col :span="18" :column="4">
            <span style="font-size: 25px">{{ titleOrder }}</span>
            <span style="color: red; padding-left: 10px">{{ order_code_string }}</span>
          </el-col>
          <el-col :span="6">
            <el-descriptions direction="vertical">
              <el-descriptions-item
                label="编号"
                label-align="center"
                align="center"
                label-class-name="light-blue"
              >
                <el-input v-model="form.code" disabled placeholder="自动生成"></el-input
              ></el-descriptions-item>
              <el-descriptions-item
                label="单据日期"
                label-align="center"
                align="center"
                label-class-name="light-blue"
              >
                <el-date-picker
                  v-model="form.billdate"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  disabled
                />
              </el-descriptions-item>
            </el-descriptions>
          </el-col>
        </el-row>
      </el-form>
      <!-- <sc-water-mark ref="wm" text="已审核" subtext="誉卓纱线"> -->
      <sk-tabs type="border-card">
        <el-tab-pane ref="tab" label="基础信息">
          <el-form
            :model="form"
            :rules="rules"
            ref="dialogForm"
            label-width="70px"
            label-position="right"
          >
            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="6" align="客户">
                    <el-form-item label="客户" prop="customer_id">
                      <skAutoChoose
                        :disabled="form.iscustomer == 1"
                        v-model="form.customer.name"
                        :params="[
                          {
                            name: {
                              type: 'nlr',
                              value: 'YZ',
                            },
                          },
                        ]"
                        :name="'customer'"
                        :assign="form"
                        @select="cunstomerSelect"
                      >
                      </skAutoChoose>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="派车单" prop="car_id">
                      <skAutoChoose
                        v-model="form.car.code"
                        :name="'car'"
                        :assign="form"
                        @select="selectCar"
                      >
                      </skAutoChoose>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="运输商" prop="car.company_id">
                      <skAutoChoose
                        v-model="form.car.company.name"
                        :name="'factory'"
                        :asKey="'company_id'"
                        :assign="form.car"
                        :params="[{ category_id: 110 }]"
                      >
                      </skAutoChoose>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="运费" prop="car.amount">
                      <el-input v-model="form.car.amount" clearable></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item label="备注" prop="remark">
                      <el-input v-model="form.remark" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form>

          <sc-VxeTable
            ref="save"
            :gridEvts="gridEvts"
            :data="form.details"
            :gridOps="gridOps"
            :height="300"
            :tablecode="'market_backwarehouse_save'"
          >
          </sc-VxeTable>
        </el-tab-pane>
        <el-tab-pane label="附件">
          <sk-upload
            v-model="form.attachments"
            :limit="10"
            draggable
            tip="单个文件不要超过10M,请上传图像格式文件"
          >
          </sk-upload>
        </el-tab-pane>
      </sk-tabs>
    </sc-water-mark>
    <!-- </sc-water-mark> -->
    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        v-if="form.status_id == 0"
        :loading="isSaveing"
        @click="submit()"
        >保 存</el-button
      >
    </template>
  </el-dialog>
  <skBrowserChoose
    v-model="dialog.openChooseDlg"
    :name="'storage_browser'"
    @close="dialog.openChooseDlg = false"
    @select="additems"
    :params="getParams"
  >
  </skBrowserChoose>
  <skBrowserChoose
    v-model="dialog.openChooseDlgWid"
    :name="'storage_wip_browser'"
    @close="dialog.openChooseDlgWid = false"
    @select="additemsWip"
  >
  </skBrowserChoose>
  <pack
    v-if="dialog.pack"
    ref="packDialog"
    @success="packSuccess"
    @closed="dialog.pack = false"
  ></pack>
</template>

<script>
import skBrowserChoose from "@/components/skBrowserChoose";
import skDicSelect from "@/components/skDicSelect";
import skAutoChoose from "@/components/skAutoChoose";
import skSelectGroup from "@/components/skSelectGroup";
import pack from "./pack";
import { ElMessageBox } from "element-plus";
import XEUtils from "xe-utils";
export default {
  emits: ["success", "closed"],
  components: {
    skAutoChoose,
    skDicSelect,
    skBrowserChoose,
    skSelectGroup,
    pack,
  },
  data() {
    return {
      mode: "add",
      dialog: { openChooseDlg: false, openChooseDlgWid: false, pack: false },
      order_code: [],
      ARBalance: 0,
      titleOrder: "发货",
      credit_limit: 0,
      gridEvts: {
        choose: () => (this.dialog.openChooseDlg = true),
        choosewip: () => (this.dialog.openChooseDlgWid = true),
        delete: async ({ button }) => {
          const type = await ElMessageBox.confirm("您确定要删除该数据?");
          if (type === "confirm") {
            this.$API.market.backwarehouse.deleteItems
              .get({
                ids: button.selectRecords.map(v => v.id),
              })
              .then(res => {
                if (res.code == "200") {
                  let count = 0;
                  this.form.details.filter((item, index) => {
                    button.selectRecords.some(v => v == item) &&
                      this.form.details.splice(index - count++, 1);
                  });
                }
              });
          }
        },
        edit: ({ button }) => {
          this.dialog.pack = true;
          this.$nextTick(() => {
            this.$refs.packDialog.open().setData(button.selectRecords[0]);
          });
        },
      },
      titleMap: {
        add: "新增",
        edit: "编辑",
      },
      form: {
        id: "",
        car: { company: {} },
        status_id: 0,
        customer_id: null,
        customer: { name: "" },
        collection: [],
        department_id: 0,
        billdate: XEUtils.toDateString(new Date(), "yyyy-MM-dd"),
        code: "",
        iscustomer: null,
        remark: "",
        details: [],
        attachments: [],
      },
      addTemplate: {
        billdate: XEUtils.toDateString(new Date(), "yyyy-MM-dd"),
        state: 1,
        trade_id: 0,
      },
      rules: {
        billdate: { required: true, message: "请选择单据日期" },
        customer_id: { required: true, message: "请选择客户" },
      },
      visible: false,
      isSaveing: false,
      gridOps: {
        height: 300,
        columns: [
          {
            field: "auxiliary_quantity",
            event: {
              keyup: ({ row, params }) => {
                row["se_auxiliary_quantity"] = row["auxiliary_quantity"];
                params.$grid.updateFooter();
              },
            },
          },
        ],
      },
    };
  },
  mounted() {},

  computed: {
    order_code_string() {
      return this.order_code.toString();
    },
  },
  watch: {
    "form.details": {
      handler(val) {
        val.filter(v => this.computeQuantity(v));
      },
      deep: true,
    },
  },
  methods: {
    computeQuantity(deltail) {
      let quantity = 0,
        auxiliary_quantity = 0;

      deltail.packs.filter(v => {
        quantity += parseFloat(v.quantity);
        auxiliary_quantity += parseFloat(v.auxiliary_quantity);
      });
      if (deltail.quantity != quantity) {
        deltail.quantity = quantity;
      }
      if (deltail.auxiliary_quantity != auxiliary_quantity) {
        deltail.auxiliary_quantity = auxiliary_quantity;
      }
    },
    getParams() {
      let params = {};
      if (this.form.customer_id) params.customer_id = this.form.customer_id;
      return [params];
    },

    selectCar(data) {
      if (typeof data.code == "undefined") {
        data = { company: {} };
        this.form.car_id = 0;
      }
      this.form.car = data;
    },
    getKey: row => {
      return (
        row.color_name +
        "_" +
        row.dyelot +
        "_" +
        row.company_id +
        "_" +
        row.material_id +
        "_" +
        row.is_wip
      );
    },
    additemsWip(items) {
      this.dialog.openChooseDlgWid = false;
      items.map(defrow => {
        defrow.is_wip = 1;
        defrow.wip_id = defrow.id;
        defrow.id = "key_" + defrow.id;
        defrow.custno = defrow.open_card.custno;
        defrow.customer_id = defrow.company_id;
        defrow.quantity = defrow.se_quantity = parseFloat(defrow.faultle_quantity);
        defrow.auxiliary_quantity = 1;
        defrow["merge_key"] = this.getKey(defrow);
        delete defrow.available_mquantity;
        let find = this.form.details.find(v => v.merge_key == defrow.merge_key);
        if (find) {
          if (find.packs.find(v => v.id == defrow.id)) {
            return ElMessageBox.alert("该库存已选择过了，无法再次选择！");
          }
          find.se_quantity = (
            parseFloat(find.se_quantity) + parseFloat(defrow.se_quantity)
          ).toFixed(2);

          find.packs.push(defrow);
        } else {
          let row = this.$TOOL.objCopy(defrow);
          row["packs"] = [defrow];
          row.price = 0;
          this.form.details.push(row);
        }
      });
    },
    additems(items) {
      this.dialog.openChooseDlg = false;
      items.map(defrow => {
        defrow.is_wip = 0;
        defrow.id = "key_" + defrow.id;
        defrow.customer_id = defrow.customer_id ?? 0;
        defrow.quantity = defrow.se_quantity = parseFloat(defrow.available_quantity);
        defrow.auxiliary_quantity = parseFloat(defrow.available_auxiliary_quantity);
        defrow["merge_key"] = this.getKey(defrow);
        delete defrow.available_mquantity;
        let find = this.form.details.find(v => v.merge_key == defrow.merge_key);
        if (find) {
          if (find.packs.find(v => v.id == defrow.id)) {
            return ElMessageBox.alert("该库存已选择过了，无法再次选择！");
          }
          find.se_quantity = (
            parseFloat(find.se_quantity) + parseFloat(defrow.se_quantity)
          ).toFixed(2);

          find.packs.push(defrow);
        } else {
          let row = this.$TOOL.objCopy(defrow);
          row["packs"] = [defrow];
          row.price = 0;
          this.form.details.push(row);
        }
      });
    },

    cunstomerSelect(data) {
      this.credit_limit = data.credit_limit;
      this.ARBalance = data.ARBalance;
    },

    //显示
    open(mode = "add") {
      this.mode = mode;

      this.visible = true;
      this.$nextTick(() => {
        if (this.form.status_id == 1) {
          this.$refs.wm.create();
        } else {
          this.$refs.wm.clear();
        }
      });
      return this;
    },

    //表单提交方法
    submit() {
      this.$refs.dialogForm1.validate(valid => {
        if (valid)
          this.$refs.dialogForm.validate(async valid => {
            if (valid) {
              this.isSaveing = true;

              var res = await this.$API.market.backwarehouse.save.post(this.form);
              this.isSaveing = false;
              if (res.code == 200) {
                this.$emit("success", this.form, this.mode);
                this.visible = false;
                this.$message.success("操作成功");
              }
            }
          });
      });
    },
    async getItems(code) {
      var res = await this.$API.market.backwarehouse.info.get({
        filter: [{ code: code }],
      });
      if (res.code == 200) {
        Object.assign(this.form, this.$TOOL.removeNull(res.data));
      }
    },

    //表单注入数据
    async setData(data) {
      await this.getItems(data.code);
    },
  },
};
</script>

<style>
.addicon .el-select {
  width: calc(100% - 24px);
}

.addicon .el-input__wrapper {
  border-top-right-radius: 0px;
  border-bottom-right-radius: 0px;
}

.addicon .el-button--small {
  border-top-left-radius: 0px;
  border-bottom-left-radius: 0px;
}
</style>
